package com.example.music.widgets;

import android.content.Context;
import android.util.AttributeSet;
import android.view.View;
import android.widget.RadioGroup;

/**
 * 自定义RadioGroup
 * @author ZhangZhaoCheng
 */
public class SelfRadioGroup extends RadioGroup {
    private Context mContext;

    public SelfRadioGroup(Context context) {
        super(context);
        mContext = context;
    }

    public SelfRadioGroup(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        int height = 0;
        int width = 0;
        int rows = 0;
        /**
         * 获得此ViewGroup上级容器为其推荐的宽和高，以及计算模式
         */
        int widthMode = MeasureSpec.getMode(widthMeasureSpec);
        int heightMode = MeasureSpec.getMode(heightMeasureSpec);
        int sizeWidth = MeasureSpec.getSize(widthMeasureSpec);
        int sizeHeight = MeasureSpec.getSize(heightMeasureSpec);
        // 计算出所有的childView的宽和高
        measureChildren(widthMeasureSpec, heightMeasureSpec);

        for (int index = 0; index < getChildCount(); index++) {
            final View child = this.getChildAt(index);
            width += child.getMeasuredWidth();
            if (rows == 0) {
                height = Math.max(height, child.getMeasuredHeight());
            }
            //如果数据的宽度大于整个屏幕的宽度 row行数++
            if (width > sizeWidth) {
                rows++;
                height += child.getMeasuredHeight();
                width = child.getMeasuredWidth();
            }
        }
        setMeasuredDimension(widthMeasureSpec, heightMeasureSpec);
    }

    @Override
    protected void onLayout(boolean arg0, int left, int top, int right,
                            int bottom) {
        final int count = getChildCount();
        int width = left;
        int height = top;
        int row = 0;
        int lastBottom = 0;
        for (int i = 0; i < count; i++) {
            final View child = this.getChildAt(i);
            int childWidth = child.getMeasuredWidth();
            int childHeight = child.getMeasuredHeight();
            int cl = 0, ct = 0, cr = 0, cb = 0;
            width += childWidth;
            if (row == 0) {
                height = childHeight;
            }
            if (width > right) {
                width = left + childWidth;
                height = lastBottom + childHeight;
                row++;
            }
            cl = width - childWidth;
            ct = height - childHeight;
            cr = width;
            cb = height;
            child.layout(cl, ct, cr, cb);
            lastBottom = cb;
        }
    }
}